# -*- coding: utf-8 -*-
import sys
sys.path.append("../..")
from db.mysql import MysqlClient
import aiohttp, asyncio
from itertools import product
from common.helper import Helper
from common.config import *
from urllib.parse import urlencode
import json


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "昆仑方舟一号保险"

    def genProductInfo(self):
        plan = {
            "days": ["1y"],
            "people_count": ["1"],
            "socialSec": ["Y", "N"],
            "money": ["100000", "200000"],
            "payType": ["一次交清"],
            "accident_medical": [str(i) for i in range(0, 21)],
            "accident_hospital": [str(i) for i in range(0, 7)],
        }

        for v in product(plan["days"], plan["people_count"], plan["socialSec"], plan["money"], plan["payType"],
                         plan["accident_medical"], plan["accident_hospital"]):
            data = Helper.formatProductInfo(plan, v)
            data["accident_medical"] = data["accident_medical"] + "000" if int(data["accident_medical"]) > 0 else "0"
            data["accident_hospital"] = data["accident_hospital"] + "0/天" if int(data["accident_hospital"]) > 0 else "0"

            yield data

    # 异步爬虫
    async def requestJson(self, dt):

        data = self.filterPayload(dt)

        payload = urlencode(data).replace("+", "")

        async with pool:
            async with aiohttp.ClientSession() as session:
                async with session.post(url=domain[self.name]["url"], headers=domain[self.name]["header"],
                                        data=payload) as resp:
                    res = await resp.text()
                    if "insurerPrem" in res:
                        price = Helper.decimalParse(json.loads(res)["data"]["data"]["insureds"][0]["insurerPrem"])
                        data = {
                            "name": self.name,
                            "company": "昆仑健康保险",
                            "price": price
                        }
                        data.update(dt)
                        Helper.mergeTable(self.name, self.mysql, data)

    # filterPayload
    def filterPayload(self, data=None):

        socialSec = "0" if data["socialSec"] == "N" else "1"

        init_item = [{"dutyCode": "103001", "dutyAmnt": data["money"]}]
        if data["accident_medical"] == "0":
            pass
        else:
            init_item.append({"dutyCode": "103002", "dutyAmnt": data["accident_medical"]})
        if data["accident_hospital"] == "0":
            pass
        else:

            init_item.append({"dutyCode": "103003", "dutyAmnt": data["accident_hospital"].replace("/天", "")})
        stringJson = ""
        for x in init_item:
            stringJson += json.dumps(x) + ","
        stringJson = stringJson.strip(",")
        payload = {
            'insuredsStr': '[{"birthday": "", "sex": null, "planInfos": [{"riskCode": "A187", "mainRiskCode": "A187", "planCode": "49", "planPeriod": "12个月", "payType": "0","payEndYearFlag": "","payEndYear": 0,"dutys":[' + stringJson + ']}],"socialSec":' + socialSec + '}]',
            'isOrder': '0',
            'productID': '45',
        }
        return payload

    def asyncTask(self):
        tasks = [self.requestJson(data) for data in self.genProductInfo()]
        global pool
        pool = asyncio.Semaphore(5)
        event_loop = asyncio.get_event_loop()
        event_loop.run_until_complete(asyncio.gather(*tasks))
        event_loop.close()
